<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item >
        <el-tabs
          v-model="queryParams.typeId"
          class="demo-tabs"
          @tab-change="handleQuery"
        >
          <el-tab-pane label="全部" value="" />
          <el-tab-pane v-for="item in subjectTypeList" :label="item.typeName" :value="item.typeId" :key="item.typeId" />
        
        </el-tabs>
      </el-form-item><br>
      <el-form-item label="科目编码" prop="subjectCode">
        <el-input
          v-model="queryParams.subjectCode"
          placeholder="请输入科目编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科目名称" prop="subjectName">
        <el-input
          v-model="queryParams.subjectName"
          placeholder="请输入科目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['voucher:subject:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="subjectList"
      row-key="subjectId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="序号">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="科目编码" prop="subjectCode" />
      <el-table-column label="科目名称" align="center" prop="subjectName" />
      <el-table-column label="科目类型" align="center" prop="typeName" />
      <el-table-column label="余额方向" align="center" prop="balanceDirection">
        <template #default="scope">
          <dict-tag
            :options="voucher_borrower"
            :value="scope.row.balanceDirection"
          />
        </template>
      </el-table-column>
      <el-table-column label="辅助核算项" align="center" prop="auxiliaryItems">
        <template #default="scope">
          <dict-tag
            :options="voucher_accounting"
            :value="
              scope.row.auxiliaryItems
                ? scope.row.auxiliaryItems.split(',')
                : []
            "
          />
        </template>
      </el-table-column>
      <el-table-column label="状态 " align="center" prop="isEnabled">
        <template #default="scope">
          <dict-tag :options="is_disabled" :value="scope.row.isEnabled" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['voucher:subject:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['voucher:subject:add']"
            >新增</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['voucher:subject:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改会计科目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="subjectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="科目编码" prop="subjectCode">
          <el-input v-model="form.subjectCode" placeholder="请输入科目编码" />
        </el-form-item>
        <el-form-item label="科目名称" prop="subjectName">
          <el-input v-model="form.subjectName" placeholder="请输入科目名称" />
        </el-form-item>
        <el-form-item label="余额方向" prop="balanceDirection">
          <el-radio-group v-model="form.balanceDirection">
            <el-radio
              v-for="dict in voucher_borrower"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="科目类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择科目类型">
            <el-option
              v-for="dict in subjectTypeList"
              :key="dict.typeId"
              :label="dict.typeName"
              :value="parseInt(dict.typeId)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="辅助核算" prop="auxiliaryItems">
          <el-checkbox-group v-model="form.auxiliaryItems">
            <el-checkbox
              v-for="dict in voucher_accounting"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态" prop="isEnabled">
          <el-radio-group v-model="form.isEnabled">
            <el-radio
              v-for="dict in is_disabled"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上一级" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="subjectOptions"
            :props="{
              value: 'subjectId',
              label: 'subjectName',
              children: 'children',
            }"
            value-key="subjectId"
            placeholder="请选择上级科目"
            check-strictly
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Subject">
import {
  listSubject,
  getSubject,
  delSubject,
  addSubject,
  updateSubject,
  getTypeAll,
} from "@/api/voucher/subject";

const { proxy } = getCurrentInstance();
const { voucher_accounting, is_disabled, voucher_borrower } = proxy.useDict(
  "voucher_accounting",
  "is_disabled",
  "voucher_borrower"
);

const subjectList = ref([]);
const subjectOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    subjectCode: null,
    subjectName: null,
    typeId: null,
  },
  rules: {
    subjectCode: [
      { required: true, message: "科目编码不能为空", trigger: "blur" },
    ],
    subjectName: [
      { required: true, message: "科目名称不能为空", trigger: "blur" },
    ],
    typeId: [
      { required: true, message: "科目类型不能为空", trigger: "change" },
    ],
    balanceDirection: [
      { required: true, message: "余额方向不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
const subjectTypeList = ref([]);

//查询类型下拉框列表
function getTypeList() {
  getTypeAll().then((response) => {
    subjectTypeList.value = response.data;
  });
}

/** 查询会计科目列表 */
function getList() {
  loading.value = true;
  listSubject(queryParams.value).then((response) => {
    subjectList.value = proxy.handleTree(
      response.data,
      "subjectId",
      "parentId"
    );
    loading.value = false;
  });
}

/** 查询会计科目下拉树结构 */
function getTreeselect() {
  listSubject().then((response) => {
    subjectOptions.value = [];
    const data = { subjectId: 0, subjectName: "顶级节点", children: [] };
    data.children = proxy.handleTree(response.data, "subjectId", "parentId");
    subjectOptions.value.push(data);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    subjectId: null,
    subjectCode: null,
    subjectName: null,
    typeId: null,
    balanceDirection: null,
    auxiliaryItems: [],
    isEnabled: null,
    parentId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    isDeleted: null,
  };
  proxy.resetForm("subjectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.subjectId) {
    form.value.parentId = row.subjectId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加会计科目";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.subjectId;
  }
  getSubject(row.subjectId).then((response) => {
    form.value = response.data;
    form.value.auxiliaryItems = form.value.auxiliaryItems.split(",");
    open.value = true;
    title.value = "修改会计科目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["subjectRef"].validate((valid) => {
    if (valid) {
      form.value.auxiliaryItems = form.value.auxiliaryItems.join(",");
      if (form.value.subjectId != null) {
        updateSubject(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSubject(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除会计科目编号为"' + row.subjectId + '"的数据项？')
    .then(function () {
      return delSubject(row.subjectId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getTypeList();
getList();
</script>
